import 'package:flutter/services.dart';

class NumberTextInputFormatter extends TextInputFormatter {
  static const defaultDouble = 0.001;

  ///允许的小数位数，-1代表不限制位数
  int digit;
  ///允许的整数位数，-1代表不限制位数
  int integerLength;

  NumberTextInputFormatter({this.digit = -1, this.integerLength = -1});
  static double strToFloat(String str, [double defaultValue = defaultDouble]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }

  ///获取目前的小数位数
  static int getValueDigit(String value) {
    if (value.contains(".")) {
      return value.split(".")[1].length;
    } else {
      return -1;
    }
  }

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    } else if (value == "-") {
      value = "-";
      selectionIndex++;
    } else if (value != "" && value != defaultDouble.toString() && strToFloat(value, defaultDouble) == defaultDouble || getValueDigit(value) > digit) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    }

    if (integerLength != -1) {
      if (newValue.text.contains('.')) {
        int pointIndex = newValue.text.indexOf('.');
        String beforePoint = newValue.text.substring(0, pointIndex);
        //小数点前内容大于integerLength
        if (beforePoint.length > integerLength) {
          value = oldValue.text;
          selectionIndex = oldValue.selection.end;
        }
      } else {
        if (newValue.text.length > integerLength) {
          value = oldValue.text;
          selectionIndex = oldValue.selection.end;
        }
      }
    }

    return TextEditingValue(
      text: value,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}